#pragma once
#include <sys/epoll.h>
#include <iostream>
#include "Log.hpp"
#include "Com.hpp"
#include <unistd.h>
using namespace LogMoudle;
class Epoller
{
public:
    Epoller() : epollfd(-1)
    {
        createEpoll(128);
        if (epollfd < 0)
        {
            LOG(LogLevel::ERROR) << "epollfd创建失败";
            exit(1);
        }   
    }
    void ModEventHepler(int fd,uint32_t events,int oper)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = fd;
        int n = epoll_ctl(epollfd, oper, fd, &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl修改事件失败";
            exit(1); 
        }
    }
    void ModEvent(int fd,uint32_t events){
        ModEventHepler(fd,events,EPOLL_CTL_MOD);
    }
    void DelEvent(int fd){
        ModEventHepler(fd,0,EPOLL_CTL_DEL);
    }
    void AddEvent(int fd,uint32_t events){
        ModEventHepler(fd,events,EPOLL_CTL_ADD);
    }
    int WaitEvent(struct epoll_event events[], int maxevents, int timeout = -1)
    {
        int n = epoll_wait(epollfd, events, maxevents, timeout);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_wait等待事件失败";
            exit(1);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "epoll_wait等待超时";
        }
        return n;
    }
    void createEpoll(int size)
    {
        epollfd = epoll_create(size);
    }
    ~Epoller()
    {
        if (epollfd >= 0)
        {
            close(epollfd);
            LOG(LogLevel::INFO) << "epollfd关闭成功";
        }
    }

private:
    int epollfd;
};